/**
 * Copyright (C) 2009-2012 Couchbase, Inc.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALING
 * IN THE SOFTWARE.
 */

package net.crawwle.career.analyze.servlet;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Properties;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.crawwle.career.analyze.couchbase.ConnectionManager;

import org.apache.log4j.Logger;

import com.google.gson.Gson;

/**
 * The BeerServlet handles all Install-related HTTP Queries.
 *
 * The BeerServlet is used to handle all HTTP queries under the /install namespace.
 * The "web.xml" defines a wildcard route for every /install/* route, so the
 * doGet() method needs to determine what should be dispatched.
 */
public class InstallServlet extends HttpServlet {

	  /**
	   * The Logger to use.
	   */
	  private static final Logger logger = Logger.getLogger(
			  InstallServlet.class.getName());

	/**
	 * Dispatch all incoming GET HTTP requests.
	 *
	 * Since the /install/* routes are wildcarded and will all end up here, the
	 * method needs to check agains the PATH (through getPathInfo()) and
	 * determine which helper method should be called. The helper method then
	 * does the actual request and response handling.
	 *
	 * @param request
	 *            the HTTP request object.
	 * @param response
	 *            the HTTP response object.
	 * @throws ServletException
	 * @throws IOException
	 */
	@Override
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		logger.info("InstallServlet get requests:" + request.getPathInfo());

		handleIndex(request, response);
	}

	/**
	 * Store and validate the Install form.
	 *
	 * @param req
	 * @param resp
	 * @throws ServletException
	 * @throws IOException
	 */
	@Override
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		logger.info("InstallServlet post requests:" + request.getPathInfo());

		HashMap<String, Object> responseResult = new HashMap<String, Object>();

		// Proxyサーバ
		Properties conf = new Properties();
		InputStream inputStream = new FileInputStream(
				"/opt/conf/crawwle.properties");
		try {
			conf.load(inputStream);
		} catch (IOException e) {
			// TODO 自動生成された catch ブロック
			e.printStackTrace();
			request.setAttribute("msg",
					"the crawwle.properties file does not exist.");
			logger.error("the crawwle.properties file does not exist.");
			request.getRequestDispatcher("/WEB-INF/install/index.jsp").forward(
					request, response);
		}
		//HashMap<String, String> msg = new HashMap<String, String>();
		Enumeration<String> params = request.getParameterNames();
		while (params.hasMoreElements()) {
			String key = params.nextElement();
			logger.info(key + ":" + request.getParameter(key));
			if (key.equals("node_url")) {
				conf.setProperty("coubase.server.node.url",
						request.getParameter(key));
			} else if (key.equals("databucket_job")) {
				conf.setProperty("coubase.server.bucket.career",
						request.getParameter(key));
			} else if (key.equals("databucket_keyword")) {
				conf.setProperty("coubase.server.bucket.career",
						request.getParameter(key));
			} else if (key.equals("esCluster")) {
				conf.setProperty("elastic.search.cluster",
						request.getParameter(key));
			}

		}

		Gson gson = new Gson();

		try {
			ConnectionManager.reConnect(
					conf.getProperty("coubase.server.node.url"),
					conf.getProperty("coubase.server.bucket.career"),
					conf.getProperty("coubase.server.bucket.career"),conf.getProperty("elastic.search.cluster"));
		} catch (Exception e) {
			// TODO 自動生成された catch ブロック
			e.printStackTrace();
			responseResult.put("msg_error","ご指定のサーバーとつながらないですので、あらためて設定値の確認をお願いします。");
			response.setContentType("application/json; charset=UTF-8");
			PrintWriter out = response.getWriter();
			out.print(gson.toJson(responseResult));
			out.flush();
			return;
		}
		conf.store(new FileOutputStream("/opt/conf/crawwle.properties"), null);

		//request.setAttribute("msg", "設定を反映しました.");
		//responseResult.put("jobs", jobs);

		responseResult.put("msg", "設定は無事に完了しました.");
		response.setContentType("application/json; charset=UTF-8");
		PrintWriter out = response.getWriter();
		out.print(gson.toJson(responseResult));
		out.flush();


	}





	/**
	 * Handle the /install action.
	 *
	 * Based on a defined Couchbase View (Install/brewery_beers), the install are
	 * loaded, arranged and passed to the JSP layer. Google GSON is used to
	 * handle the JSON encoding/decoding.
	 *
	 * @param request
	 *            the HTTP request object.
	 * @param response
	 *            the HTTP response object.
	 * @throws IOException
	 * @throws ServletException
	 */
	private void handleIndex(HttpServletRequest request,
			HttpServletResponse response) throws IOException, ServletException {

		//Proxyサーバ
	    Properties conf = new Properties();
		InstallInfo setting = new InstallInfo();
		InputStream inputStream = new FileInputStream("/opt/conf/crawwle.properties");
		try {
			conf.load(inputStream);
			setting.setNode_url(conf.getProperty("coubase.server.node.url"));
			setting.setJobBucket(conf.getProperty("coubase.server.bucket.career"));
			setting.setKeywordBucket(conf.getProperty("coubase.server.bucket.keyword"));
			setting.setProxyHost(conf.getProperty("proxy.host"));
			setting.setProxyPort(conf.getProperty("proxy.port"));

			setting.setElasticSearchClusterName(conf.getProperty("elastic.search.cluster"));

			request.setAttribute("setting", setting);
			inputStream.close();
		} catch (IOException e) {
			// TODO 自動生成された catch ブロック
			e.printStackTrace();
			request.setAttribute("msg", "the crawwle.properties file does not exist.");
			logger.error( "the crawwle.properties file does not exist.");
		}


		request.getRequestDispatcher("/WEB-INF/install/index.jsp").forward(request,
				response);
	}
}
